package gorails.com;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;




import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class TripPlannerActivity extends Activity {
	private Button pickLine;
	private Button viewTrip;
	private Button changeTime;
	private String origin ;
	private TableRow destRow;
	private TableRow planRow;
	private Spinner destSpinner;
	
    static final int CHANGE_TIME_DIALOG = 0;

    ProgressDialog progressDialog;
	//----------------
	private DBAdapter dbAdapter;
	
	private static final String LINE_COLUMN = "metra";
	
	
	private static final String TABLE_STATION = "station";
	private static final String TABLE_LINE = "line";
	private static final String COLUMN_UPN = "UnionPacificNorth";
	private static final String COLUMN_MDN = "MilwaukeeDistrictNorth";
	private static final String COLUMN_NCS = "NorthCentralService";
	private static final String COLUMN_UPNW = "UnionPacificNorthwest";
	private static final String COLUMN_MDW = "MilwaukeeDistrictWest";
	private static final String COLUMN_UPW = "UnionPacificWest";
	private static final String COLUMN_BNSF = "BNSFRailway";
	private static final String COLUMN_HC = "HeritageCorridor";
	private static final String COLUMN_SWS = "SouthwestService";
	private static final String COLUMN_RID = "RockIslandDistrict";
	private static final String COLUMN_MED = "MetraElectricDistrict";
	private static final String COLUMN_SIZE = "stationSize";
	//----- UPN Time Insert
	
	private static final String TABLE_UPN_OW = "UnionPacificNorth_OW";
	private static final String TABLE_UPN_OS = "UnionPacificNorth_OS";
	private static final String TABLE_UPN_OH = "UnionPacificNorth_OH";
	private static final String TABLE_UPN_IW = "UnionPacificNorth_IW";
	private static final String TABLE_UPN_IS = "UnionPacificNorth_IS";
	private static final String TABLE_UPN_IH = "UnionPacificNorth_IH";

	
	//-------
	
	
	
	private ArrayList<String> list;
	private SQLiteDatabase db;
	private SharedPreferences pref;
	private static int currentVersion = 0;
	private static int savedVersion = 0;
	private Thread updateDB;
	ProgressDialog updater;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tripplanner);
        pickLine = (Button) findViewById(R.id.pickLineB);
        viewTrip = (Button) findViewById(R.id.ViewTrips);
        changeTime = (Button) findViewById(R.id.changeTime);
        destRow = (TableRow) findViewById(R.id.destRow);
        planRow = (TableRow) findViewById(R.id.planTripRow);
        destSpinner = (Spinner)findViewById(R.id.destSpinner);
        
        
        // Database Update
       	pref = getSharedPreferences("Database",MODE_PRIVATE);
       	dbAdapter = new DBAdapter(this);
        db =dbAdapter.getDB();
       	currentVersion = db.getVersion();
       	savedVersion = pref.getInt("version", 0);
       	updateDB = new Thread(new Runnable() {
	        public void run() {
	        	updateDatabase(savedVersion,currentVersion);
	        	insertTimes(savedVersion,currentVersion);
	        }
	    });
       	
       	if(currentVersion>savedVersion && savedVersion==0){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					"Your App must first setup the train schedules please press create to begin. \n" +
					"This should not take more than 1 minute depending on the phone")
					.setCancelable(false)
					.setTitle("Create Database")
					.setPositiveButton("Create",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// Action for 'Yes' Button
									updater = ProgressDialog.show(TripPlannerActivity.this, "", 
					                        "Creating. Please wait...", true);
									updater.show();
									updateDB.start();
								}
							});
			builder.show();
       	}
       	else if(currentVersion>savedVersion && savedVersion>0){
       		AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					"To keep schedules up to date, the database needs to be updated please press update to begin. \n" +
					"This should not take more than 1 minute depending on the phone")
					.setCancelable(false)
					.setTitle("Update")
					.setPositiveButton("Update",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// Action for 'Yes' Button
									ProgressDialog updater = ProgressDialog.show(TripPlannerActivity.this, "", 
					                        "Updating. Please wait...", true);
									updater.show();
									updateDB.start();
									
								}
							});
			
			builder.show();
       	}
       	
       
        pickLine.setOnClickListener(new OnClickListener() {        
			@Override
			public void onClick(View v) {
				Intent i = new Intent(TripPlannerActivity.this, PickLine.class);
		        startActivity(i);
			}
        	
        });
        changeTime.setOnClickListener(new OnClickListener() {        
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder;
				final AlertDialog alertDialog;

				LayoutInflater inflater = (LayoutInflater) TripPlannerActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
				View layout = inflater.inflate(R.layout.time_picker_dialog,(ViewGroup) findViewById(R.id.layout_root));

				final Button departBy = (Button) layout.findViewById(R.id.departButton);
				final Button arriveBy = (Button) layout.findViewById(R.id.arriveButton);
				final Button donePickTime = (Button) layout.findViewById(R.id.doneButton);
				final TimePicker mTimeSet = (TimePicker) layout.findViewById(R.id.timepick);
				final DatePicker mDateSet = (DatePicker) layout.findViewById(R.id.datePicker1);
				builder = new AlertDialog.Builder(TripPlannerActivity.this);
				builder.setView(layout);
				builder.setTitle("Pick Data/Time");
				Trip.getInstance().setArriveOrDepart(false); //default is depart by
				
				departBy.setEnabled(false);
				//set current time
				int cMin = mTimeSet.getCurrentMinute();
				int cHour = mTimeSet.getCurrentHour();								
				Trip.getInstance().setTime(cHour, cMin);
				
				
				int cDay = mDateSet.getDayOfMonth();
				int cMonth = mDateSet.getMonth();
				int cYear = mDateSet.getYear();
				Log.d("DATE", "Day="+cDay+" Month="+cMonth+" Year="+cYear+" Hour="+cHour+" Min="+cMin);
				Trip.getInstance().setDate(cDay, cMonth, cYear);
				//done initial set
				Calendar cal = Calendar.getInstance();
				int currentMonth = cal.get(Calendar.MONTH);
				int currentDay = cal.get(Calendar.DAY_OF_MONTH);
				int currentYear = cal.get(Calendar.YEAR);
				int currentMin = cal.get(Calendar.MINUTE);
				int currentHour = cal.get(Calendar.HOUR_OF_DAY);
				Log.d("Comp Date", "Day="+currentDay+" Month="+currentMonth+" Year="+currentYear+" Hour="+currentHour+" Min="+currentMin);
				if(cDay>currentDay || cMonth>currentMonth || cYear>currentYear || cMin>currentMin || cHour>currentHour){
					Trip.getInstance().isInFuture(true);
					Log.d("TripPlannerActiviy","Trip in Future");
				}
				else{
					Trip.getInstance().isInFuture(false);
					Log.d("TripPlannerActiviy","Trip Current");
				}
				
				departBy.setOnClickListener(new OnClickListener() {        
					@Override
					public void onClick(View v) {
						departBy.setEnabled(false);
						arriveBy.setEnabled(true);						
						//depart is false;
						Trip.getInstance().setArriveOrDepart(false);
					}
				});
				arriveBy.setOnClickListener(new OnClickListener() {        
					@Override
					public void onClick(View v) {
						departBy.setEnabled(true);
						arriveBy.setEnabled(false);
						//depart is false;
						Trip.getInstance().setArriveOrDepart(true);
					}
				});
				alertDialog = builder.create();
				alertDialog.show();
				
				donePickTime.setOnClickListener(new OnClickListener() {        
					@Override
					public void onClick(View v) {
						
						int cMin = mTimeSet.getCurrentMinute();
						int cHour = mTimeSet.getCurrentHour();
						
						Trip.getInstance().setTime(cHour, cMin);
						
						
						int cDay = mDateSet.getDayOfMonth();
						int cMonth = mDateSet.getMonth();
						int cYear = mDateSet.getYear();
						Log.d("DATE", "Day="+cDay+" Month="+cMonth+" Year="+cYear+" Hour="+cHour+" Min="+cMin);
						Trip.getInstance().setDate(cDay, cMonth, cYear);
						Calendar cal = Calendar.getInstance();
						int currentMonth = cal.get(Calendar.MONTH);
						int currentDay = cal.get(Calendar.DAY_OF_MONTH);
						int currentYear = cal.get(Calendar.YEAR);
						int currentMin = cal.get(Calendar.MINUTE);
						int currentHour = cal.get(Calendar.HOUR_OF_DAY);
						Log.d("Comp Date", "Day="+currentDay+" Month="+currentMonth+" Year="+currentYear+" Hour="+currentHour+" Min="+currentMin);
						if( cMin>currentMin || cHour>currentHour){
							Trip.getInstance().isInFuture(true);
							Log.d("TripPlannerActiviy","Trip in Future");
						}
						else{
							Trip.getInstance().isInFuture(false);
							Log.d("TripPlannerActiviy","Trip Current");
						}
						Toast.makeText(getApplicationContext(), Trip.getInstance().getDateTimeString(), 5000).show();
						changeTime.setText(Trip.getInstance().getDateTimeString());
						viewTrip.setEnabled(true); //once set time, enable them to move forward
						viewTrip.setVisibility(View.VISIBLE);
						alertDialog.dismiss();
					}
				});      
			}
        });
        viewTrip.setOnClickListener(new OnClickListener() {        
			@Override
			public void onClick(View v) {				
				Intent i = new Intent(TripPlannerActivity.this, ViewTrip.class);
		        startActivity(i);
			}	
        });
        
    }
	 protected Dialog onCreateDialog(int id) {
	        switch(id) {
	        case CHANGE_TIME_DIALOG:
	            progressDialog = new ProgressDialog(this);
	            progressDialog.setMessage("Updating....");
	            progressDialog.setTitle("Update");
	            return progressDialog;
	        default:
	            return null;
	        }
	    }

	    @Override
	    protected void onPrepareDialog(int id, Dialog dialog) {
	        switch(id) {
	        case CHANGE_TIME_DIALOG:
	            progressDialog.setProgress(0);
	            break;
	        default: break;
	        }
	    }
	
	@Override
	public void onResume(){
		super.onResume();
		origin = Trip.getInstance().getOrigin();
		destRow = (TableRow) findViewById(R.id.destRow);
		planRow = (TableRow) findViewById(R.id.planTripRow);
		viewTrip.setVisibility(View.GONE);
		viewTrip.setEnabled(false);
		destSpinner = (Spinner)findViewById(R.id.destSpinner);
		if(origin!=null){
			pickLine.setText(origin);
			destRow.setVisibility(View.VISIBLE);
			planRow.setVisibility(View.VISIBLE);
			list = getLineStations(Trip.getInstance().getLinePosition(),Trip.getInstance().getStationPosition());
			DestinationAdapter destAdapter = new DestinationAdapter(this, list);
			destSpinner.setAdapter(destAdapter);

			destSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
			    	int sPos = Trip.getInstance().getStationPosition();
			    	if(pos > sPos){
			    		//since we removed the origin from the list
			    		//any number after the origin will be 1 position less 
			    		//so we comp by adding 1 
			    		String dest = list.get(pos);
			    		Log.d("TripPlanner.DestSpinner>pos", "dest= "+dest+" pos="+(pos+1));
			    		Trip.getInstance().setDestination(dest);
				    	Trip.getInstance().setDestinationPos(pos+1);
			    	}
			    	else if(pos==0 && sPos == 0){
			    		String dest = list.get(pos);
			    		Log.d("TripPlanner.DestSpinner==0", "dest= "+dest+" pos="+(pos+1));
			    		Trip.getInstance().setDestination(dest);
				    	Trip.getInstance().setDestinationPos((pos+1));
			    	}
			    	else{
			    		String dest = list.get(pos);
			    		Log.d("TripPlanner.DestSpinner<=pos", "dest= "+dest+" pos="+(pos));
			    		Trip.getInstance().setDestination(dest);
				    	Trip.getInstance().setDestinationPos((pos));
			    	}
			    	
			    	
			    }

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
				}
			});
			
        }
	}
	
	
	public ArrayList<String> getLineStations(int linePosition,int stationPosition){    	    	

		dbAdapter = new DBAdapter(this);
		SQLiteDatabase db = dbAdapter.getDB();
		ArrayList<String> LineList = new ArrayList<String>();
		String rawQuery = "SELECT " + COLUMN_SIZE + " FROM " + TABLE_LINE
				+ " WHERE " + COLUMN_SIZE + "!=0";
		Cursor a = db.rawQuery(rawQuery, null);
		a.moveToPosition(-1);
		int linePos = 0;
		int currentSize = 0;
		while (a.moveToNext()) {
			if (linePos == linePosition) {
				currentSize = a.getInt(0);
				Log.d("StationSize(0," + linePos + ")", "Selectedval="
						+ currentSize);
			}
			linePos++;
		}
		a.close();

		String desiredColumn = "";
		String[] columns = new String[] { COLUMN_UPN, COLUMN_MDN, COLUMN_NCS,
				COLUMN_UPNW, COLUMN_MDW, COLUMN_UPW, COLUMN_BNSF, COLUMN_HC,
				COLUMN_SWS, COLUMN_RID, COLUMN_MED };

		int i = 0;
		while (i < linePosition) {
			i++;
		}
		desiredColumn = columns[i];

		String rawQuery2 = "SELECT " + desiredColumn + " FROM " + TABLE_STATION
				+ " WHERE " + desiredColumn + "!=" + "\""
				+ Trip.getInstance().getOrigin() + "\"";
		Cursor c = db.rawQuery(rawQuery2, null);

		c.moveToPosition(-1);
		int j = 0;
		while (c.moveToNext()) {

			LineList.add(c.getString(0));
			//Log.d("Adding Station(" + j + ",0)", c.getString(0));
			j++;
		}

		if (c != null && !c.isClosed()) {
			c.close();
		}
		db.close();
		return LineList;
	}
	public void updateDatabase(int savedVersion, int currentVersion){
    	if(currentVersion > savedVersion){
			SharedPreferences.Editor editor = pref.edit();
			editor.putInt("version", currentVersion);
			editor.commit();
			currentVersion++;
			db.setVersion(currentVersion);

			

			Log.d("Metra Lines", "Database insert complete");
			// System.gc();
			String[] UPN_stations = new String[] { "Kenosha",
					"Winthrop Harbor", "Zion", "Waukegan", "North Chicago",
					"Great Lakes", "Lake Bluff", "Lake Forest",
					"Fort Sheridan", "Highwood", "Highland Park", "Ravinia",
					"Ravinia Park", "Braeside", "Glencoe", "Hubbard Woods",
					"Winnetka", "Indian Hill", "Kenilworth", "Wilmette",
					"Evanston Central Street", "Evanston Davis Street",
					"Evanston Main Street", "Rogers Park", "Ravenswood",
					"Clybourn", "Ogilvie Transportation Center" };
			String[] MDN_stations = new String[] { "Fox Lake", "Ingleside",
					"Long Lake", "Round Lake", "Grayslake",
					"Prairie Crossing/Libertyville", "Libertyville",
					"Lake Forest", "Deerfield", "Lake Cook Road", "Northbrook",
					"Glen of North Glenview", "Glenview", "Golf",
					"Morton Grove", "Edgebrook", "Forest Glen", "Mayfair",
					"Grayland", "Healy", "Western Avenue", "Union Station" };
			String[] NCS_stations = new String[] { "Antioch", "Lake Villa",
					"Round Lake Beach", "Washington St. / Grayslake",
					"Prairie Crossing / Libertyville", "Mundelein",
					"Vernon Hills", "Prairie View", "Buffalo Grove",
					"Wheeling", "Prospect Heights", "O'Hare Transfer",
					"Rosemont", "Schiller Park", "Belmont Ave / Franklin Park",
					"River Grove", "Western Avenue", "Union Station", };
			String[] UPNW_stations = new String[] { "Harvard", "McHenry",
					"Woodstock", "Crystal Lake", "Pingree Road", "Cary",
					"Fox River Grove", "Barrington", "Palatine",
					"Arlington Park (Race Track)", "Arlington Heights",
					"Mount Prospect", "Cumberland", "Des Plaines", "Dee Road",
					"Park Ridge", "Edison Park", "Norwood Park",
					"Gladstone Park", "Jefferson Park", "Irving Park",
					"Clybourn", "Ogilvie Transportation Center" };
			String[] MDW_stations = new String[] { "Big Timber Road", "Elgin",
					"National Street", "Bartlett", "Hanover Park",
					"Schaumburg", "Roselle", "Medinah", "Itasca", "Wood Dale",
					"Bensenville", "Mannheim", "Franklin Park", "River Grove",
					"Elmwood Park", "Mont Clare", "Mars", "Galewood",
					"Hanson Park", "Grand / Cicero", "Western Avenue",
					"Union Station" };
			String[] UPW_stations = new String[] { "Elburn", "La Fox",
					"Geneva", "West Chicago", "Winfield", "Wheaton",
					"College Avenue", "Glen Ellyn", "Lombard", "Villa Park",
					"Elmhursts", "Berkeley", "Bellwood", "Melrose Park",
					"Maywood", "River Forest", "Oak Park", "Kedzie",
					"Ogilvie Transportation Center" };
			String[] BNSF_stations = new String[] { "Aurora", "Route 59",
					"Naperville", "Lisle", "Belmont",
					"Downers Grove Main Street", "Fairview Avenue", "Westmont",
					"Clarendon Hills", "West Hinsdale", "Hinsdale",
					"Highlands", "Western Springs", "LaGrange Stone Avenue",
					"LaGrange Road", "Congress Park", "Brookfield",
					"Hollywood", "Riverside", "Harlem Ave", "Berwyn",
					"LaVergne", "Cicero", "Western Avenue", "Halsted",
					"Union Station" };
			String[] HC_stations = new String[] { "Joliet", "Lockport",
					"Lemont", "Willow Springs", "Summit", "Union Station" };
			String[] SWS_stations = new String[] { "Manhattan",
					"New Lenox Laraway Road", "Orland Park 179th Street",
					"Orland Park 153rd Street", "Orland Park 143rd Street",
					"Palos Park", "Palos Heights", "Worth", "Chicago Ridge",
					"Oak Lawn", "Ashburn", "Wrightwood", "Union Station" };
			String[] RID_stations = new String[] { "Joliet", "New Lenox",
					"Mokena", "Hickory Creek", "Tinley Park - 80th Ave.",
					"Tinley Park", "Oak Forest", "Midlothian", "Robbins",
					"Blue Island - Vermont St.", "Prairie St.", "123rd St.",
					"119th Street", "Morgan Park - 115th Street",
					"Morgan Park - 111th Street",
					"Beverly Hills - 107th Street",
					"Beverly Hills - 103rd Street",
					"Beverly Hills - 99th Street",
					"Beverly Hills - 95th Street",
					"Beverly Hills - 91st Street", "Brainerd",
					"103rd St., Washington Hts", "95th St. - Longwood",
					"Gresham", "35th Street / 'Lou' Jones / Bronzeville",
					"LaSalle Street Station"

			};
			String[] MED_stations = new String[] { "Blue Island", "Burr Oak",
					"Ashland", "Racine", "West Pullman", "Stewart Ridge",
					"State Street", "93rd St. (South Chicago)",
					"87th St. (South Chicago)", "83rd St. (South Chicago)",
					"79th Street (Cheltenham)", "Windsor Park", "South Shore",
					"Bryn Mawr", "Stony Island", "University Park",
					"Richton Park", "Matteson",
					"211th Street (Lincoln Highway)", "Olympia Fields",
					"Flossmoor", "Homewood", "Calumet", "Hazel Crest",
					"Harvey", "147th Street (Sibley Boulevard)", "Ivanhoe",
					"Riverdale", "Kensington / 115th Street",
					"111th Street (Pullman)", "107th Street",
					"103rd Street (Rosemoor)", "95th St., Chicago State Univ.",
					"91st Street (Chesterfield)", "87th Street (Woodruff)",
					"83rd Street (Avalon Park)", "79th St., Chatham",
					"75th Street (Grand Crossing)", "63rd Street",
					"59th St., Univ. of Chicago", "55th - 56th - 57th Street",
					"51st / 53rd Street (Hyde Park)", "47th Street (Kenwood)",
					"27th Street", "McCormick Place", "18th Street",
					"Museum Campus / 11th Street", "Van Buren Street",
					"Millennium Station"

			};
			ContentValues initialValues = new ContentValues();
			//dbAdapter = new DBAdapter(this);
			int index = 0;
			while(index<UPN_stations.length || index<MDN_stations.length || index<NCS_stations.length || index<UPNW_stations.length || index<MDW_stations.length || index<UPN_stations.length || index<BNSF_stations.length || index<HC_stations.length || index<SWS_stations.length || index<RID_stations.length || index<MED_stations.length){
				//Log.d("insert Database", "index="+index);
				if(index<UPN_stations.length){
					initialValues.put(COLUMN_UPN, UPN_stations[index]);
				}
				if(index<MDN_stations.length){
					initialValues.put(COLUMN_MDN, MDN_stations[index]);
				}
				if(index<NCS_stations.length){
					initialValues.put(COLUMN_NCS, NCS_stations[index]);
				}
				if(index<UPNW_stations.length){
					initialValues.put(COLUMN_UPNW, UPNW_stations[index]);
				}
				if(index<MDW_stations.length){
					initialValues.put(COLUMN_MDW, MDW_stations[index]);
				}
				if(index<UPW_stations.length){
					initialValues.put(COLUMN_UPW, UPW_stations[index]);
				}
				if(index<BNSF_stations.length){
					initialValues.put(COLUMN_BNSF, BNSF_stations[index]);
				}
				if(index<HC_stations.length){
					initialValues.put(COLUMN_HC, HC_stations[index]);
				}
				if(index<SWS_stations.length){
					initialValues.put(COLUMN_SWS, SWS_stations[index]);
				}
				if(index<RID_stations.length){
					initialValues.put(COLUMN_RID, RID_stations[index]);
				}
				if(index<MED_stations.length){
					initialValues.put(COLUMN_MED, MED_stations[index]);
				}
				db.insertWithOnConflict(TABLE_STATION, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE);
				initialValues.clear();
				index++;
			}			
			System.gc();
			initialValues.clear();

			int linesizes[] = new int[] { UPN_stations.length,
					MDN_stations.length, NCS_stations.length,
					UPNW_stations.length, MDW_stations.length,
					UPW_stations.length, BNSF_stations.length,
					HC_stations.length, SWS_stations.length,
					RID_stations.length, MED_stations.length };
			String[] lines = new String[] { "Union Pacific North",
					"Milwaukee District North", "North Central Service",
					"Union Pacific Northwest", "Milwaukee District West",
					"Union Pacific West", "BNSF Railway", "Heritage Corridor",
					"Southwest Service", "Rock Island District",
					"Metra Electric District" };

			for (int j = 0; j < linesizes.length; j++) {
				initialValues.put(COLUMN_SIZE, linesizes[j]);
				initialValues.put(LINE_COLUMN, lines[j]);
				db.insertWithOnConflict(TABLE_LINE, null, initialValues,
						SQLiteDatabase.CONFLICT_ABORT);
				initialValues.clear();
			}

		}
		db.close();
		 //updater.dismiss();
    }
	public void insertTimes(int savedVersion, int currentVersion){
    	if(currentVersion > savedVersion){
       		SharedPreferences.Editor editor = pref.edit();
       		editor.putInt("version", currentVersion);
      		 editor.commit();
      		 currentVersion++;
      		 SQLiteDatabase db = dbAdapter.getDB();
      		 db.setVersion(currentVersion);
      		 ContentValues initialValues = new ContentValues();	
      		Cursor temp = db.rawQuery("SELECT stationSize FROM line WHERE stationSize!=0", null);
    		temp.moveToPosition(-1);
    		int[] stationSize = new int[12];
    		int sPos =0;
    		while(temp.moveToNext()){
    			stationSize[sPos] = temp.getInt(0);
    			sPos++;
    		}
   
    		temp.close();
      		 //----------------------UPN-----------
    		UPN_Trains UPN = UPN_Trains.getInstance();
      		 int currentTrain = 300;
      	    for(int i = 0;i<UPN_Trains.UPN_IW_Trains.length;i++){    		
      	    	UPN_Trains.UPN_IW_Trains[i]=currentTrain;
      	    	currentTrain+=2;
      	    }
      	    
      	    currentTrain = 301;
      	    for(int i = 0;i<UPN_Trains.UPN_OW_Trains.length;i++){
      	    	UPN_Trains.UPN_OW_Trains[i]=currentTrain;
      	    	currentTrain+=2;
      	    }

    	    	
			String[] UPN_IW_Columns = new String[UPN_Trains.UPN_IW_Trains.length];
			String[] UPN_OW_Columns = new String[UPN_Trains.UPN_OW_Trains.length];
			String[] UPN_IS_Columns = new String[UPN_Trains.UPN_IS_Trains.length];
			String[] UPN_OS_Columns = new String[UPN_Trains.UPN_OS_Trains.length];
			String[] UPN_IH_Columns = new String[UPN_Trains.UPN_IH_Trains.length];
			String[] UPN_OH_Columns = new String[UPN_Trains.UPN_OH_Trains.length];
			ArrayList<String> trainTimes = new ArrayList<String>();
			int row = 0;
			initialValues = new ContentValues();
			for(int index = 0; index < UPN_IW_Columns.length; index++){
      	    	UPN_IW_Columns[index]="t"+UPN_Trains.UPN_IW_Trains[index];    			
			}			
	
			
			while(row < stationSize[0]){ //upn station size
				for(int column = 0; column < UPN_IW_Columns.length;column++){
					trainTimes = UPN.trainTimeByNumber_IW.get(column);
					if(trainTimes.get(row)!=null){
						//Log.d("TripPlanner insert", UPN_IW_Columns[column]+"("+row+","+column+")= "+trainTimes.get(row));
						initialValues.put(UPN_IW_Columns[column], trainTimes.get(row));
					}
				}
				db.insertWithOnConflict(TABLE_UPN_IW, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE);
				initialValues.clear();
				row++;
			}
				
				
			
			
			
			
			for(int index = 0; index < UPN_OW_Columns.length; index++){
  	    		UPN_OW_Columns[index]="t"+UPN_Trains.UPN_OW_Trains[index];
			}    
			row = 0;
			initialValues.clear();
			
			while(row < stationSize[0]){ //upn station size
				for(int column = 0; column < UPN_OW_Columns.length;column++){
					trainTimes = UPN.trainTimeByNumber_OW.get(column);
					if(trainTimes.get(row)!=null){
						//Log.d("TripPlanner insert", UPN_OW_Columns[column]+"("+row+","+column+")= "+trainTimes.get(row));
						initialValues.put(UPN_OW_Columns[column], trainTimes.get(row));
					}
				}
				db.insertWithOnConflict(TABLE_UPN_OW, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE);
				initialValues.clear();
				row++;
			}
			
			
			for(int index = 0; index < UPN_IS_Columns.length; index++){
				UPN_IS_Columns[index]="t"+UPN_Trains.UPN_IS_Trains[index];    			
			}			
			row = 0;
			initialValues.clear();
			while(row < stationSize[0]){ //upn station size
				for(int column = 0; column < UPN_IS_Columns.length;column++){
					//Log.d("Trip Planner IS", ""+UPN.trainTimeByNumber_IS.get(column));
					trainTimes = UPN.trainTimeByNumber_IS.get(column);
					if(trainTimes.get(row)!=null){
						initialValues.put(UPN_IS_Columns[column], trainTimes.get(row));
					}
				}
				db.insertWithOnConflict(TABLE_UPN_IS, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE);
				initialValues.clear();
				row++;
			}
			
			
			for(int index = 0; index < UPN_OS_Columns.length; index++){
				UPN_OS_Columns[index]="t"+UPN_Trains.UPN_OS_Trains[index];    			
			}
			row = 0;
			initialValues.clear();
			while(row < stationSize[0]){ //upn station size
				for(int column = 0; column < UPN_OS_Columns.length;column++){
					//Log.d("Trip Planner OS", ""+UPN.trainTimeByNumber_OS.get(column));
					trainTimes = UPN.trainTimeByNumber_OS.get(column);
					if(trainTimes.get(row)!=null){
						initialValues.put(UPN_OS_Columns[column], trainTimes.get(row));
					}
				}
				db.insertWithOnConflict(TABLE_UPN_OS, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE);
				initialValues.clear();
				row++;
			}
			
			for(int index = 0; index < UPN_IH_Columns.length; index++){
				UPN_IH_Columns[index]="t"+UPN_Trains.UPN_IH_Trains[index];    			
			}
			row = 0;
			initialValues.clear();
			while(row < stationSize[0]){ //upn station size
				for(int column = 0; column < UPN_IH_Columns.length;column++){
					trainTimes = UPN.trainTimeByNumber_IH.get(column);
					if(trainTimes.get(row)!=null){
						initialValues.put(UPN_IH_Columns[column], trainTimes.get(row));
					}
				}
				db.insertWithOnConflict(TABLE_UPN_IH, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE);
				initialValues.clear();
				row++;
			}
			
			for(int index = 0; index < UPN_OH_Columns.length; index++){
				UPN_OH_Columns[index]="t"+UPN_Trains.UPN_OH_Trains[index];    			
			}	
			row = 0;
			initialValues.clear();
			while(row < stationSize[0]){ //upn station size
				for(int column = 0; column < UPN_OH_Columns.length;column++){
					trainTimes = UPN.trainTimeByNumber_OH.get(column);
					if(trainTimes.get(row)!=null){
						initialValues.put(UPN_OH_Columns[column], trainTimes.get(row));
					}
				}
				db.insertWithOnConflict(TABLE_UPN_OH, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE);
				initialValues.clear();
				row++;
			}
			//-------------------End UPN-------------------------
			
			
			
			
			db.close();   
       	}   	
                  
           updater.dismiss();
    }
	
}